package cn.rsa.aiwangren.advice;

import cn.rsa.aiwangren.annotation.Decrypt;
import cn.rsa.aiwangren.config.SecretKeyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.lang.reflect.Type;
import java.util.Objects;


/**
 * 对请求进行处理
 *
 * @author xiangtianlei
 * @date 2024/04/09
 */
@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private boolean encrypt;
    /**
     * 私钥
     */
    private String privateKey;

    @Autowired
    private SecretKeyConfig secretKeyConfig;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(Decrypt.class) && secretKeyConfig.isOpen()) {
            encrypt = true;
            String channel = methodParameter.getMethod().getAnnotation(Decrypt.class).value();
            try {
                privateKey = secretKeyConfig.getKeyPair(channel).getPrivateKey();
            } catch (Exception e) {
                log.error("The: The {} channel may not have found the corresponding private key", channel);
            }
        }
        return encrypt;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                           Class<? extends HttpMessageConverter<?>> converterType) {
        if (encrypt) {
            try {
                return new DecryptHttpInputMessage(inputMessage, this.privateKey, secretKeyConfig.getCharset(), secretKeyConfig.isShowLog(), secretKeyConfig.getMAX_DECRYPT_BLOCK());
            } catch (Exception e) {
                log.error("Decryption failed", e);
            }
        }
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
